'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  console.log('submitServiceRating 接收到的参数:', event);
  
  if (!event.uniIdToken) {
    return {
      code: 401,
      msg: '用户未登录'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  try {
    const { uid: userId } = await uniIDIns.checkToken(event.uniIdToken);
    if (!userId) {
      return { code: 401, msg: '用户未登录' };
    }

    const { rating, feedback = '', sessionId } = event;

    if (!rating || rating < 1 || rating > 5) {
      return { code: 400, msg: '评分必须在1-5之间' };
    }

    console.log('提交服务评价，用户ID:', userId, '评分:', rating);

    // 保存评价到数据库
    const ratingData = {
      userId: userId,
      rating: rating,
      feedback: feedback,
      sessionId: sessionId || 'default_session',
      createTime: new Date()
    };

    const result = await db.collection('serviceRatings').add(ratingData);

    console.log('评价保存结果:', result);

    return {
      code: 200,
      msg: '评价提交成功',
      data: {
        _id: result.id,
        ...ratingData
      }
    };

  } catch (error) {
    console.error('提交服务评价失败:', error);
    return {
      code: 500,
      msg: '提交评价失败: ' + error.message
    };
  }
};
